//
//  HJAddBankeVC.m
//  project
//
//  Created by jc on 2019/4/15.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJAddBankeVC.h"
//#import "HJAddBankDetailVC.h"
#import "HJNavigationViewController.h"

@interface HJAddBankeVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *bankNum;

/**
 选择卡号的方式
 */
//@property (weak, nonatomic) IBOutlet UIButton *bankSelecte;

/**
 银行卡名字
 */
@property (weak, nonatomic) IBOutlet UITextField *bankName;

/**
 银行卡类型
 */
@property (weak, nonatomic) IBOutlet UITextField *bankType;

/**
 手机号
 */
@property (weak, nonatomic) IBOutlet UITextField *phone;
/**
 验证码
 */
@property (weak, nonatomic) IBOutlet UITextField *smsCode;

/**
 发送验证码
 */
@property (weak, nonatomic) IBOutlet UIButton *sendCode;

/**
 同意协议 默认同意
 */
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;

/**
 下一步
 */
@property (weak, nonatomic) IBOutlet UIButton *netBtn;

/**
 查看协议
 */
@property (weak, nonatomic) IBOutlet UIButton *xieyiBtn;

@property (nonatomic, assign) NSInteger timeout;// 倒计时

@property (nonatomic,strong) HJAddModel * addCardModel;

/**
 是否添加成功
 */
@property (nonatomic,assign) BOOL isAddCard;

@end

@implementation HJAddBankeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navTitle = @"银行卡绑定";
    self.leftNavImageName = @"back_black_left";
//    self.bankNum.text = @"6228481101100634315";
    self.bankNum.delegate = self;
//    [self.bankNum addTarget:self action:@selector(textFieldDidChangeValue:) forControlEvents:UIControlEventEditingDidEnd];
    [self.sendCode rounded:UIRectCornerAllCorners radius:5];
    [self.netBtn rounded:UIRectCornerAllCorners radius:5];
    [self configBtnSmsCode];
}

- (void)configBtnSmsCode {
    @weakify(self)
    [[self.xieyiBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        NSURL * url = [[NSBundle mainBundle] URLForResource:@"agreement.html" withExtension:nil];
        HJWebViewController * webVC =[HJWebViewController new];
        webVC.navTitle = @"乐见用户协议";
        webVC.isPushLogin = YES;
        webVC.URLString = url.absoluteString;
        HJNavigationViewController * nav = [[HJNavigationViewController alloc]initWithRootViewController:webVC];
        [self presentViewController:nav animated:YES completion:nil];
    }];
    
    // 是否同意协议
    [[self.agreeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        x.selected = !x.selected;
        self.agreeBtn.selected = x.selected;
    }];
    
    // 验证码
    [[self.sendCode rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self.view endEditing:NO];
        [self countDown:x];
        [self sendHttpSmsCode];
    }];
    
    [[self.phone.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        return value.length >=11;
    }] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.phone.text = [x substringToIndex:11];
    }];
    
    [[self.smsCode.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        return value.length >=6;
    }]subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.smsCode.text = [x substringToIndex:6];
    }];
    
    RAC(self.sendCode, userInteractionEnabled) = [RACSignal combineLatest:@[self.phone.rac_textSignal] reduce:^id(NSString *phone) {
        @strongify(self)
        if ([CommonTools isMobileNumber:phone]) {
            if (self->_timeout <= 0) { // 上一个验证码的倒计时已经结束 或未开始 才可以获取新的验证码
                self.sendCode.backgroundColor = [UIColor blackColor];
                self.smsCode.userInteractionEnabled = YES;
                return @YES;
            } else {
                self.smsCode.userInteractionEnabled = NO;
                return @NO;
            }
        }else {
            if (phone.length >=11) {
                [YFHud showError:@"您填写的手机号不正确!"];
            }
            self.smsCode.userInteractionEnabled = NO;
            self.sendCode.backgroundColor = [UIColor lightGrayColor];
            self.netBtn.backgroundColor = [UIColor lightGrayColor];
            return @NO;
        }
    }];
    
    RAC(self.netBtn,userInteractionEnabled) = [RACSignal combineLatest:@[self.bankNum.rac_textSignal,self.phone.rac_textSignal,self.smsCode.rac_textSignal,RACObserve(self.agreeBtn, selected)] reduce:^id (NSString * cardNum, NSString * phone, NSString * smsCode, NSNumber *selecte) {
        @strongify(self)
        if (cardNum.length >= 15 &&phone.length ==11 && smsCode.length ==6 && [selecte boolValue]) {
            self.netBtn.backgroundColor = [UIColor colorWithHex:0x2a2a2a];
            return @YES;
        }
        self.netBtn.backgroundColor = [UIColor lightGrayColor];
        return @NO;
    }];
    
    [[self.netBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self nextBtnClicked];
    }];
}

-(void)didClickLeftNavAction {
    if (self.isAdd && self.jsApiTestBlock) {
        self.jsApiTestBlock(NO);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- 监听textfield值得变化
-(void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.text.length>=15 && [CommonTools isBankCardNumber:textField.text]) {
        WS(weakSelf)
        NSString * bankNameUrl =[Api stringByAppendingString:CheckBankApi];
        [HJHttpTool get:bankNameUrl params:@{@"bankCardNo":self.bankNum.text} success:^(HJResponeds *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.addCardModel = [HJAddModel yy_modelWithDictionary:result.data];
                self.bankName.text = self.addCardModel.name;
                self.bankType.text = [self.addCardModel.type isEqualToString:@"DC"] ? @"储蓄卡" : @"信用卡";
            });
        } failure:^(id result) {
            [weakSelf showErrorHUDWithError:@"请输入正确的银行卡号！"];
        }];
    }
}
//-(void)textFieldDidChangeValue:(UITextField *)textfield {

//}

#pragma mark -- 下一步按钮点击事件
-(void)nextBtnClicked {
    [self showTextHUDWithPleaseWait];
    WS(weakSelf)
    NSString * AddBankUrl = [Api stringByAppendingString:AddBankApi];
    NSMutableDictionary * param =[NSMutableDictionary dictionary];
    param[@"bankId"] = self.addCardModel.bankId;
    param[@"mobile"] = self.phone.text;
    param[@"code"] = self.smsCode.text;
    param[@"bankCardNum"]= self.bankNum.text;
    param[@"bankCardName"] = self.bankName.text;
    param[@"bankCardType"] = self.addCardModel.type;
    
    [HJHttpTool post:AddBankUrl params:param success:^(HJResponeds *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideTextHud];
            if (self.isAdd) {
                if (weakSelf.jsApiTestBlock) {
                    weakSelf.jsApiTestBlock(YES);
                }
            }else {
                if (weakSelf.updateListBlock) {
                    weakSelf.updateListBlock();
                }
            }
            [self.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(id result) {
        [weakSelf hideTextHud];
        [weakSelf showErrorHUDWithError:result];
    }];
}

#pragma mark - Private Methods 发送验证码
-(void)sendHttpSmsCode {
    NSString * url = [Api stringByAppendingString:BankSmsApi];
    [HJHttpTool post:url params:@{@"mobile":self.phone.text} success:^(HJResponeds *result) {
        [YFHud showSuccess:@"发送成功"];
    } failure:^(id result) {
        [YFHud showError:result];
    }];
}

- (void)countDown:(UIButton *)btn {
    _timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if (self->_timeout <= 0) {
            // 倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.backgroundColor = [UIColor blackColor];
                btn.userInteractionEnabled = YES;
                [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
            });
        } else {
            NSString *strTime = [NSString stringWithFormat:@"重新发送(%.2ld)", (long)self->_timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.smsCode.userInteractionEnabled = YES;
                [btn setTitle:strTime forState:UIControlStateNormal];
                btn.userInteractionEnabled = NO;
                btn.backgroundColor = [UIColor lightGrayColor];
            });
            self->_timeout--;
        }
    });
    dispatch_resume(_timer);
}

@end






@implementation HJAddModel

-(NSString *)description {
    return [self yy_modelDescription];
}

@end
